const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navHeight: app.globalData.navHeight,
    navTop: app.globalData.navTop,
    searchWidth: app.globalData.menuButtonRight,
    navRight: app.globalData.menuButtonwidth,
    keydown_number: 0,
    listarr: [], //创建数组
    input_value: "", //value值
    hostarr: [], //热门搜索接收请求存储数组  
    name_focus: true, //获取焦点
    inputClose: false //清空输入框
  },

  navBack: function(e) {
    try {
      wx.navigateBack({
        delta: 1,
        fail: function(e) {

        }
      })
    } catch (e) {
      console.log(e)
    }
  },

  //取值input判断输入框内容修改按钮
  _onTap: function(e) {
    var that = this;
    var value = e.detail.value;
    if (e.detail.cursor != 0) {
      that.setData({
        inputClose: true,
        keydown_number: 1,
        keydesc: true
      })
      wx.request({
        url: util.api + api.SearchProduct,
        data: {
          BUSINESS_PARAMETERS: {
            userToekn: loginStatus.token,
            PostStaId: 22,
            combo: 0,
            cid: "",
            keyword: value,
            sort: 0,
            pageNo: 1,
            brandIds: "",
            origin: "",
            IsZiti: 0,
            minprice: 0,
            maxprice: 0,
            first: true
          },
          SYSTEM_PARAMETERS: {
            APP_ID: "M_P_G001",
            METHOD_ID: 0,
            ACCESS_TOKEN: "1w2Re3bE^og38",
            TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
            SIGN: "string"
          }
        },
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        success: function (res) {
          if (res.statusCode == 200) {
            if (res.data.MESSAGE.MESSAGE_CODE == 1) {
              var lilyData = res.data.RESULT['<ProductList>k__BackingField']['<List>k__BackingField'];
              var search_num = [];
              try {
                var search_val = lilyData.filter(p => p['<Title>k__BackingField'].match(e.detail.value) || p['<ProductItemID>k__BackingField'] == e.detail.value);
                for (let i = 0; i < search_val.length; i++) {
                  search_num.push(search_val[i]['<Title>k__BackingField'])
                }
                that.setData({
                  keyItem: search_num
                })
              } catch (e) {

              }
            }

            if (res.data.MESSAGE.MESSAGE_CODE == 0) {}
          }

        },
        fail: function (res) {},
        complete: function (res) {}
      })
    } else {
      that.setData({
        inputClose: false,
        keydown_number: 0,
        keydesc: false
      })
    }

  },

  //搜索方法
  searchFood: function(e) {
    var that = this;
    this.setData({
      name_focus: true
    })
    let value = e.detail.value;
    this.setData({
      input_value: value,
      keydown_number: 1,
      inputClose: true,
      keydesc: false
    })
    if (this.data.keydown_number == 1) {
      //把获取的input值插入数组里面
      let arr = this.data.listarr;
      util.navigateTo('../productlist/productlist?search=' + value)
      that.setData({
        name_focus: false
      })
      //判断取值是手动输入还是点击赋值
      if (this.data.input_value == "") {
        // 判断数组中是否已存在
        let arrnum = arr.indexOf(value);

        if (arrnum != -1) {
          // 删除已存在后重新插入至数组
          arr.splice(arrnum, 1)
          arr.unshift(value);

        } else {
          arr.unshift(value);
        }

      } else {

        let arr_num = arr.indexOf(this.data.input_value);
        if (arr_num != -1) {
          arr.splice(arr_num, 1)
          arr.unshift(this.data.input_value);
        } else {
          arr.unshift(this.data.input_value);
        }

      }
      //存储搜索记录
      wx.setStorage({
        key: "list_arr",
        data: arr
      })


      //取出搜索记录
      wx.getStorage({
        key: 'list_arr',
        success: function(res) {
          that.setData({
            listarr: res.data
          })
        }
      })

    }

  },

  closeInput: function() {
    this.setData({
      input_value: '',
      keydown_number: 0,
      inputClose: false,
      keydesc: false
    });

  },


  //清除搜索记录
  delete_list: function() {
    //清除当前数据
    this.setData({
      listarr: []
    });
    //清除缓存数据
    wx.removeStorage({
      key: 'list_arr'
    })
  },

  //点击赋值到input框
  this_value: function(e) {
    var that = this;
    let value = e.currentTarget.dataset.text;
    this.setData({
      input_value: value,
      keydown_number: 1,
      inputClose: true
    })
    if (this.data.keydown_number == 1) {
      //把获取的input值插入数组里面
      let arr = this.data.listarr;
      util.navigateTo('../productlist/productlist?search=' + value)
      that.setData({
        keydesc: false,
        name_focus: false
      })
      //判断取值是手动输入还是点击赋值
      if (this.data.input_value == "") {
        // 判断数组中是否已存在
        let arrnum = arr.indexOf(value);

        if (arrnum != -1) {
          // 删除已存在后重新插入至数组
          arr.splice(arrnum, 1)
          arr.unshift(value);

        } else {
          arr.unshift(value);
        }

      } else {

        let arr_num = arr.indexOf(this.data.input_value);
        if (arr_num != -1) {
          arr.splice(arr_num, 1)
          arr.unshift(this.data.input_value);
        } else {
          arr.unshift(this.data.input_value);
        }

      }
      //存储搜索记录
      wx.setStorage({
        key: "list_arr",
        data: arr
      })


      //取出搜索记录
      wx.getStorage({
        key: 'list_arr',
        success: function(res) {
          that.setData({
            listarr: res.data
          })
        }
      })

    }

  },

  unique(array) {
    return array.filter(function(el, index, arr) {
      return index == arr.indexOf(el);
    })
  },

  change_list: function() {
    var that = this;
    // wx.request({
    //   url: util.api + 'search/hot.json',
    //   method: 'GET',
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   success: function(res) {
    //     var arrlist = res.data.result;
    //     var lastArr = [];
    //     for (var i = 0; i < 8; i++) {
    //       var index = parseInt(Math.random() * arrlist.length);
    //       lastArr.push(arrlist[index]);
    //       for (var j = 0; j < lastArr.length - 1; j++) {

    //         if (lastArr[i] == lastArr[j]) {
    //           lastArr.pop();
    //           --i;
    //         }
    //       }
    //     }
    //     that.setData({
    //       hostarr: lastArr
    //     })
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    // wx.request({
    //   url: util.api + 'search/hot.json',
    //   method: 'GET',
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   success: function(res) {
    //     var arrlist = res.data.result;
    //     arrlist.splice(8, arrlist.length - 1)
    //     that.setData({
    //       hostarr: arrlist
    //     })
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //读取缓存历史搜索记录
    wx.getStorage({
      key: 'list_arr',
      success: function(res) {
        that.setData({
          listarr: res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      keydesc: false
    })
  }

})